package com.csx.governance.traffic.adapter.outbound.openfeign;

import com.csx.governance.traffic.adapter.outbound.openfeign.async.TrafficAsyncFeignClient;
import com.csx.governance.traffic.core.interceptor.TrafficHandlerInterceptorRunner;
import feign.AsyncClient;
import feign.Client;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;

/**
 * <p> Feign Client的后置处理器 </p>
 * <p> 主要作用是将 容器中原生Feign Client {@link Client} 包装为自定义 {@link TrafficFeignClient}</p>
 * @author cuisongxu
 * @date 2023/3/18 18:23
 */
public class TrafficFeignClientWrapProcessor implements BeanPostProcessor {

    private final TrafficHandlerInterceptorRunner handlerInterceptorRunner;

    public TrafficFeignClientWrapProcessor(TrafficHandlerInterceptorRunner handlerInterceptorRunner) {
        this.handlerInterceptorRunner = handlerInterceptorRunner;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        if(bean instanceof Client) {
            bean = new TrafficFeignClient((Client) bean, handlerInterceptorRunner);
        } else if(bean instanceof AsyncClient) {
            bean = new TrafficAsyncFeignClient((AsyncClient) bean, handlerInterceptorRunner);
        }
        return BeanPostProcessor.super.postProcessAfterInitialization(bean, beanName);
    }
}
